import AuthForm from "../../component/AuthForm/index.tsx";
import { useConfig } from "../../hook/D8dConfigProvider.tsx";
import { setLocalStorage } from "../../utils/fun.ts";
import type { FormItemConfigs } from "../../global.ts";
import type { AuthMode } from "../../component/AuthForm/index.tsx";
import type { CSSProperties } from "react";
import { useNavigate } from "../../hook/useNavigate.ts";

export type AuthDisplayMode = 'simple' | 'professional';

export interface AuthLayoutConfig {
  /* 页面背景配置 */
  background?: {
    color?: string;
    image?: string;
    style?: CSSProperties;
  };
  /* 左上角配置 */
  topLeft?: {
    logo?: React.ReactNode;
    title?: React.ReactNode;
    style?: CSSProperties;
  };
  /* 右上角配置 */
  topRight?: {
    content?: React.ReactNode;
    style?: CSSProperties;
  };
  /* 页脚配置 */
  footer?: {
    content?: React.ReactNode;
    style?: CSSProperties;
  };
  /* 表单左侧配置 */
  leftContent?: {
    content?: React.ReactNode;
    style?: CSSProperties;
  };
  /* 表单右侧配置 */
  rightContent?: {
    content?: React.ReactNode;
    style?: CSSProperties;
  };
  /* 表单容器样式 */
  formContainerStyle?: CSSProperties;
}

export interface AuthFormConfig {
  /* 显示模式: simple-简洁模式, professional-专业模式 */
  mode?: AuthDisplayMode;
  /* 登录表单配置 */
  loginFormConfig?: FormItemConfigs[];
  /* 注册表单配置 */
  registerFormConfig?: FormItemConfigs[];
  /* 认证页面标题 */
  authTitle?: string;
  /* 按钮文本 */
  buttonText?: {
    login?: string;
    register?: string;
  };
  /* 成功提示文本 */
  successTip?: {
    login?: string;
    register?: string;
  };
  /* 布局配置 */
  layout?: AuthLayoutConfig;
}

interface AuthPageProps {
  /* 路由加载器 默认是 admin */
  loaderPath?: string;
  /* 认证模式 */
  authMode?: AuthMode;
  /* 认证表单配置 */
  authConfig?: AuthFormConfig;
  /* 登录成功后的重定向路径，默认为 /{loaderPath} */
  redirectPath?: string;
}

export default function AuthPage({ 
  loaderPath = 'admin', 
  authMode = 'login-only',
  authConfig,
  redirectPath
}: AuthPageProps) {
  const { setToken, setUserInfo, apiUrl, tokenKey, setUserMenu } = useConfig();
  const navigate = useNavigate();

  // 默认登录表单配置
  const defaultLoginFormConfig: FormItemConfigs[] = [
    {
      label: "用户名",
      name: "username",
      type: "input",
      placeholder: "请输入用户名",
      rules: [{ required: true, message: "请填写用户名" }],
    },
    {
      label: "密码",
      name: "password",
      type: "password",
      placeholder: "请输入密码",
      rules: [{ required: true, message: "请填写密码" }],
    },
  ];

  // 默认注册表单配置
  const defaultRegisterFormConfig: FormItemConfigs[] = [
    {
      label: "用户名",
      name: "username",
      type: "input",
      placeholder: "请设置用户名",
      rules: [
        { required: true, message: "请填写用户名" },
        { min: 4, message: "用户名至少4个字符" }
      ],
    },
    {
      label: "密码",
      name: "password",
      type: "password",
      placeholder: "请设置密码",
      rules: [
        { required: true, message: "请填写密码" },
        { min: 6, message: "密码至少6个字符" }
      ],
    },
    {
      label: "确认密码",
      name: "confirmPassword",
      type: "password",
      placeholder: "请确认密码",
      rules: [
        { required: true, message: "请确认密码" },
        ({ getFieldValue }) => ({
          validator(_, value) {
            if (!value || getFieldValue('password') === value) {
              return Promise.resolve();
            }
            return Promise.reject(new Error('两次输入的密码不一致'));
          },
        }),
      ],
    },
    {
      label: "手机号",
      name: "phone",
      type: "input",
      placeholder: "请输入手机号",
      rules: [
        { required: true, message: "请填写手机号" },
        { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" }
      ],
    },
    {
      label: "邮箱",
      name: "email",
      type: "input",
      placeholder: "请输入邮箱",
      rules: [
        { required: true, message: "请填写邮箱" },
        { type: "email", message: "请输入正确的邮箱格式" }
      ],
    },
  ];

  // 登录成功回调
  const handleLoginSuccess = (res: any) => {
    console.log("登录成功", res);
    setLocalStorage(tokenKey, res?.token);
    setToken(res?.token);
    setUserInfo(res?.user);
    setUserMenu(res?.rolePermissions?.menuList)
    
    // 使用指定的重定向路径或默认路径
    const targetPath = redirectPath || `/${loaderPath}`;
    navigate(targetPath);
  };

  // 注册成功回调
  const handleRegisterSuccess = (res: any) => {
    console.log("注册成功", res);
    // 注册成功后可以自动登录或跳转到登录标签页
  };

  // 简洁模式的渲染
  const renderSimpleMode = () => (
    <div style={{
      width: "100vw",
      height: "100vh",
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      background: "#f5f5f5",
    }}>
      <div style={{
        width: "360px",
      }}>
        <AuthForm
          title={authConfig?.authTitle || "后台管理系统"}
          loginApiUrl={apiUrl?.login}
          registerApiUrl={apiUrl?.register}
          loginFormConfig={authConfig?.loginFormConfig || defaultLoginFormConfig}
          registerFormConfig={authConfig?.registerFormConfig || defaultRegisterFormConfig}
        loginSuccessCallback={handleLoginSuccess}
        registerSuccessCallback={handleRegisterSuccess}
        successTip={authConfig?.successTip || {
          login: "登录成功",
          register: "注册成功，请登录"
        }}
        buttonText={authConfig?.buttonText || {
          login: "登录",
          register: "注册"
        }}
        defaultTab="login"
          authMode={authMode}
        />
      </div>
    </div>
  );

  // 专业模式的渲染
  const renderProfessionalMode = () => (
    <div style={{
      width: "100vw",
      height: "100vh",
      display: "flex",
      flexDirection: "column",
      background: authConfig?.layout?.background?.color || "#f5f5f5",
      backgroundImage: authConfig?.layout?.background?.image ? `url(${authConfig.layout.background.image})` : undefined,
      backgroundSize: "cover",
      backgroundPosition: "center",
      ...authConfig?.layout?.background?.style,
    }}>
      {/* 顶部区域 */}
      <div style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        padding: "20px 40px",
      }}>
        {/* 左上角 */}
        {authConfig?.layout?.topLeft && (
          <div style={authConfig.layout.topLeft.style}>
            {authConfig.layout.topLeft.logo}
            {authConfig.layout.topLeft.title}
          </div>
        )}
        
        {/* 右上角 */}
        {authConfig?.layout?.topRight && (
          <div style={authConfig.layout.topRight.style}>
            {authConfig.layout.topRight.content}
          </div>
        )}
      </div>

      {/* 主要内容区域 */}
      <div style={{
        flex: 1,
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        padding: "20px",
      }}>
        {/* 表单左侧内容 */}
        {authConfig?.layout?.leftContent && (
          <div style={authConfig.layout.leftContent.style}>
            {authConfig.layout.leftContent.content}
          </div>
        )}

        {/* 表单容器 */}
        <div style={{
          background: "#fff",
          padding: "40px",
          borderRadius: "8px",
          boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
          ...authConfig?.layout?.formContainerStyle,
        }}>
          <AuthForm
            title={authConfig?.authTitle || "后台管理系统"}
            loginApiUrl={apiUrl?.login}
            registerApiUrl={apiUrl?.register}
            loginFormConfig={authConfig?.loginFormConfig || defaultLoginFormConfig}
            registerFormConfig={authConfig?.registerFormConfig || defaultRegisterFormConfig}
            loginSuccessCallback={handleLoginSuccess}
            registerSuccessCallback={handleRegisterSuccess}
            successTip={authConfig?.successTip || {
              login: "登录成功",
              register: "注册成功，请登录"
            }}
            buttonText={authConfig?.buttonText || {
              login: "登录",
              register: "注册"
            }}
            defaultTab="login"
            authMode={authMode}
          />
        </div>

        {/* 表单右侧内容 */}
        {authConfig?.layout?.rightContent && (
          <div style={authConfig.layout.rightContent.style}>
            {authConfig.layout.rightContent.content}
          </div>
        )}
      </div>

      {/* 页脚区域 */}
      {authConfig?.layout?.footer && (
        <div style={{
          padding: "20px",
          textAlign: "center",
          ...authConfig.layout.footer.style,
        }}>
          {authConfig.layout.footer.content}
        </div>
      )}
    </div>
  );

  return authConfig?.mode === 'professional' ?renderProfessionalMode() : renderSimpleMode() ;
} 